package vn.huync.smsbackupandrestore;

import java.io.File;
import java.io.FilenameFilter;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import vn.huync.smsbackupandrestore.models.SmsModel;
import vn.huync.smsbackupandrestore.others.Utils;
import vn.huync.smsbackupandrestore.others.Utils.SyncListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.nch.smsbackupandrestore.R;

public class SmsBackupAndRestoreActivity extends Activity implements SyncListener {
	
	private static final int DIALOG_FILE_NAME = 1;
	private static final int DIALOG_LIST_VIEW_FILE = 5;
	private static final int DIALOG_DELETE_MESSAGE_CONFIRM = 6;
	private static final int DIALOG_ABOUT = 7;
	
	private static final int MENU_LOGIN = 0;
	private static final int MENU_PREFERENCE = 1;
	private static final int MENU_ABOUT = 2;
	
	static final int REQUEST_AUTHORIZATION = 2; 
	
	static final int kRateStatusToAskRate = 5;
	static final int kRateStatusRated = -1;
	static final int kRateStatusDontAskAgain = -2;
	static final String kRateKey = "rateKey";
	
	Button bBackup, bRestore, bView, bSearch, bDeleteMessage, bDeleteBackup;
	ArrayList<SmsModel> lSms;
	String[] listFile;				//list xml file exist to restore
	EditText tFileName = null;
	TextView tLastBackup;
	
	static MyApp myApp;
	int[]outArray;
	ProgressDialog progressDialog;
	
	Handler handler = new MainHandler(this);
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        myApp = (MyApp)getApplicationContext();
        
        tLastBackup = (TextView)findViewById(R.id.t_last_backup_info);
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
        
        long lastBackup = pref.getLong("last_backup", 0);
        if(lastBackup != 0){
        	Date lastBackupDate = new Date(lastBackup);
        	String sLastBackup = DateFormat.format("kk:mm dd/MM/yyyy", lastBackupDate).toString();
        	tLastBackup.setText(getString(R.string.last_backup_in) + " " + sLastBackup);
        }
        else tLastBackup.setText(R.string.have_not_backup_yet);
        
        lSms = new ArrayList<SmsModel>();
        bBackup = (Button)findViewById(R.id.b_backup);
        bBackup.setOnClickListener(onClickListener);
        bView = (Button)findViewById(R.id.b_view);
        bView.setOnClickListener(onClickListener);
        bSearch = (Button)findViewById(R.id.b_search);
        bSearch.setOnClickListener(onClickListener);
        bDeleteBackup = (Button)findViewById(R.id.b_delete_backup);
        bDeleteBackup.setOnClickListener(onClickListener);
        bDeleteMessage = (Button)findViewById(R.id.b_delete_message);
        bDeleteMessage.setOnClickListener(onClickListener);
        
        AdView adView = (AdView)this.findViewById(R.id.adView);
	    AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
	    adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
	    AdRequest adRequest = adRequestBuilder.build();
	    adView.loadAd(adRequest);
        
        bRestore = (Button)findViewById(R.id.b_restore);
        bRestore.setOnClickListener(onClickListener); 
        
        Utils.ReadSMSFromDbToList(this, myApp.lSms);
		Utils.ReadContactFromDbToList(this, myApp.lContact);
        
        //check internet connection
        if(Utils.isInternetConnected(this) == false){
        	Utils.ShowToast(this, R.string.should_turn_on_internet);
        }
        else{
        	//synchronize
            boolean isSyncOnStartup = pref.getBoolean("c_sync_on_startup", true);
            if(isSyncOnStartup == true){
            	Thread syncThread = new Thread(new Runnable() {
    				
    				public void run() {
    					
    					Utils.syncAll(myApp, getApplicationContext(), SmsBackupAndRestoreActivity.this);
    				}
    			});
    			syncThread.start();
            }
        }
        
        updateAndShowRateRequestIfNeed();
    }
    
    @Override
    protected void onResume() {
    	super.onResume();
    	CheckAppFolderAndCreate();
    }
    
    @Override
    protected Dialog onCreateDialog(int id) {
    	LayoutInflater factory = LayoutInflater.from(SmsBackupAndRestoreActivity.this);
    	switch (id) {
    	
    	// Backup 
		case DIALOG_FILE_NAME:
			final View vInputText = factory.inflate(R.layout.input_filename_alert_dialog, null);
			tFileName = (EditText)vInputText.findViewById(R.id.input_filename);
			
			AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(SmsBackupAndRestoreActivity.this);
			dialogBuilder.setTitle(R.string.t_input_filename_dialog_title);
			dialogBuilder.setView(vInputText);
			
			//click ok button of dialog which was showed after press backup button.
			dialogBuilder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
			{
				public void onClick(DialogInterface dialog, int which) {
					final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(SmsBackupAndRestoreActivity.this);
					
					Utils.ReadSMSFromDbToList(SmsBackupAndRestoreActivity.this, lSms);
					String fileName = tFileName.getText().toString();
					if(fileName.endsWith(".xml") == false)
						fileName += ".xml";
					myApp.filePath = myApp.appFolderPath + fileName;
					showProgressDialog(lSms.size());
					Thread writeXmlThread = new Thread(new Runnable() {
						
						public void run() {
							Utils.WriteFromListToXML(myApp.filePath, lSms, handler);
						}
					});
					writeXmlThread.start();
					
				}
				
			});
			dialogBuilder.setNegativeButton(android.R.string.cancel, null);
			return dialogBuilder.create();
			
		case DIALOG_LIST_VIEW_FILE:
			listFile = new String[0];
			
			dialogBuilder = new AlertDialog.Builder(SmsBackupAndRestoreActivity.this);
			dialogBuilder.setTitle(R.string.list_file_dialog_title);
			dialogBuilder.setSingleChoiceItems(listFile, 0, null);
			
			dialogBuilder.setPositiveButton(R.string.view, new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					int selectedPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
					if(selectedPosition == -1){
						Utils.ShowToast(SmsBackupAndRestoreActivity.this, R.string.have_not_choose_a_file_yet);
						return;
					}
					myApp.filePath = myApp.appFolderPath + listFile[selectedPosition];
					Intent intent = new Intent(SmsBackupAndRestoreActivity.this, ListSmsByAddressActivity.class);
					startActivity(intent);
				}
			});
							
			dialogBuilder.setNegativeButton(android.R.string.cancel, null);
			return dialogBuilder.create();
		case DIALOG_DELETE_MESSAGE_CONFIRM:
			dialogBuilder = new AlertDialog.Builder(SmsBackupAndRestoreActivity.this);
			dialogBuilder.setTitle(R.string.delete_confirm_dialog_title);
			dialogBuilder.setMessage(R.string.delete_confirm_message);
			dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);
			dialogBuilder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface arg0, int arg1) {
					getContentResolver().delete(Uri.parse("content://sms"), null, null);
				}
			});
			dialogBuilder.setNegativeButton(android.R.string.cancel, null);
			return dialogBuilder.create();
			
		case DIALOG_ABOUT:
			dialogBuilder = new AlertDialog.Builder(SmsBackupAndRestoreActivity.this);
			dialogBuilder.setTitle(R.string.about);
			dialogBuilder.setIcon(R.drawable.icon_launcher);
			dialogBuilder.setMessage(R.string.about_message);
			dialogBuilder.setPositiveButton(R.string.rate_app, new OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=com.nch.smsbackupandrestore"));
					startActivity(intent);
				}
			});
			
			dialogBuilder.setNegativeButton(R.string.close, null);
			return dialogBuilder.create();
		default:
			break;
		}
    	return super.onCreateDialog(id);
    }
    
    void showProgressDialog(int max){
		progressDialog = new ProgressDialog(this);
		progressDialog.setCancelable(false);
		progressDialog.setMessage(getString(R.string.backing_up));
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.setProgress(0);
		progressDialog.setMax(max);
		progressDialog.show();
	}
    
    private View.OnClickListener onClickListener= new View.OnClickListener() {
		
		public void onClick(View v) {
			if(v == bBackup)
			{
				showDialog(DIALOG_FILE_NAME);
			}
			else if (v == bRestore)
			{
				Intent intent = new Intent(SmsBackupAndRestoreActivity.this, RestoreActivity.class);
				startActivity(intent);
			}
			else if(v == bView){
				//showDialog(DIALOG_LIST_VIEW_FILE);
				Intent intent = new Intent(getApplicationContext(), ListFileActivity.class);
				intent.putExtra("classNextActivity", ListSmsByAddressActivity.class);
				startActivity(intent);
			}
			else if(v == bSearch){
				Intent intent = new Intent(SmsBackupAndRestoreActivity.this, SearchActivity.class);
				startActivity(intent);
			}
			else if(v == bDeleteBackup){
				Intent intent = new Intent(SmsBackupAndRestoreActivity.this, DeleteActivity.class);
				startActivity(intent);
			}
			else if(v == bDeleteMessage){
				showDialog(DIALOG_DELETE_MESSAGE_CONFIRM);
			}
		}
	};
	
	void CheckAppFolderAndCreate()
	{
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
		boolean isSaveSdCard = pref.getBoolean("is_save_sdcard", true);
		if(isSaveSdCard)
			myApp.appFolderPath = myApp.sdCardPath+"/SmsBackup/";
		else myApp.appFolderPath = ""+getCacheDir()+"/";
		
		File dir = new File(myApp.appFolderPath);
		if(dir.exists() == false || dir.isDirectory() == false)
		{
			boolean isSuccess = dir.mkdir();
			if(isSuccess == false){
				Intent intent = new Intent(this, SetupActivity.class);
				startActivity(intent);
				Toast.makeText(this, getString(R.string.cannot_create_saved_directory), Toast.LENGTH_LONG).show();
			}
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuItem item = menu.add(Menu.NONE, MENU_LOGIN, MENU_LOGIN, R.string.manage_sync_account);
		item.setIcon(R.drawable.sync_icon);
		
		item = menu.add(Menu.NONE, MENU_PREFERENCE, MENU_PREFERENCE, R.string.preference);
		item.setIcon(R.drawable.pref_icon);
		
		item = menu.add(Menu.NONE, MENU_ABOUT, MENU_ABOUT, R.string.about);
		item.setIcon(R.drawable.about);
		
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_LOGIN:
			Intent intent = new Intent(this, LogInSyncServiceActivity.class);
			startActivity(intent);
			break;
		case MENU_PREFERENCE:
			intent = new Intent(this, SetupActivity.class);
			startActivity(intent);
			break;
		case MENU_ABOUT:
			showDialog(DIALOG_ABOUT);
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onBackPressed() {
		Intent intent = new Intent();
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);

        startActivity(intent);

		super.onBackPressed();
	}
	
	@Override
	@Deprecated
	protected void onPrepareDialog(int id, Dialog dialog) {
		File dir;
		ArrayAdapter<CharSequence> adapter;
		AlertDialog ad;
		switch (id) {
		case DIALOG_FILE_NAME:
			TextView tInput = (TextView)dialog.findViewById(R.id.input_filename);
			Calendar c = Calendar.getInstance(); 
			
			int year = c.get(Calendar.YEAR);
			int month = c.get(Calendar.MONTH) + 1;
			int day = c.get(Calendar.DAY_OF_MONTH);
			
			int hour = c.get(Calendar.HOUR);
			if(c.get(Calendar.AM_PM) == Calendar.PM){
				if(hour != 12)
					hour += 12;
			}
			else{
				if(hour==12)
					hour = 0;
			}
			
			int minute = c.get(Calendar.MINUTE);
			int second = c.get(Calendar.SECOND);
			
			String fileName = 
					Integer.toString(year) + "." +
					Integer.toString(month) + "." +
					Integer.toString(day) + "." +
					Integer.toString(hour) + "." +
					Integer.toString(minute) + "." +
					Integer.toString(second) + "-" +
					"SmsBackup.xml";
			tInput.setText(fileName);
			break;
			
		case DIALOG_LIST_VIEW_FILE:
			dir = new File(myApp.appFolderPath);
			listFile = dir.list(new FilenameFilter() {
				
				public boolean accept(File dir, String filename) {
					if(filename.endsWith(".xml"))
						return true;
					else return false;
				}
			});
			
			adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.select_dialog_singlechoice, android.R.id.text1, listFile);
            ad = (AlertDialog) dialog;
            ad.getListView().setAdapter(adapter);
			break;

		default:
			break;
		}
		super.onPrepareDialog(id, dialog);
	}
	
	static class MainHandler extends Handler{
		
		WeakReference<SmsBackupAndRestoreActivity> weakRef;
		
		public MainHandler(SmsBackupAndRestoreActivity activity) {
			weakRef = new WeakReference<SmsBackupAndRestoreActivity>(activity);
		}
		
		@Override
		public void handleMessage(Message msg) {
			
			final SmsBackupAndRestoreActivity activity = weakRef.get();
			
			int numSmsBackedUp = msg.getData().getInt("numSmsBackedUp");
			activity.progressDialog.setProgress(numSmsBackedUp);
			if(activity.progressDialog.getProgress() == activity.progressDialog.getMax()){
				activity.progressDialog.dismiss();
				Utils.ShowToast(activity.getApplicationContext(), 
						numSmsBackedUp + " " + activity.getString(R.string.sms_has_been_backed_up) + 
						" " + activity.myApp.filePath);
				
				// save last backup
				SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext());
				Editor editor = pref.edit();
				Date lastBackupDate = new Date();
				editor.putLong("last_backup", lastBackupDate.getTime());
				editor.commit();
				String sLastBackup = DateFormat.format("kk:mm dd/MM/yyyy", lastBackupDate).toString();
				activity.tLastBackup.setText(activity.getString(R.string.last_backup_in) + " " + sLastBackup);
				
				//Toast.makeText(SmsBackupAndRestoreActivity.this, myApp.filePath+" saved", Toast.LENGTH_LONG).show();
				
				//synchronize
		        boolean isSyncAfterBackup = pref.getBoolean("c_sync_after_backup", true);
		        if(isSyncAfterBackup == true){
		        	Thread syncThread = new Thread(new Runnable() {
						
						public void run() {
							
							Utils.syncAll(myApp, activity.getApplicationContext(), activity);
						}
					});
					syncThread.start();
		        }
			}
		}
	}
	
	public void onSyncDone() {
	}

	public void onUserRecoverableAuthIOException(
			UserRecoverableAuthIOException e) {
		startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
	}

	public void onSyncDropboxDone(final int upload, final int download) {
		
		runOnUiThread(new Runnable() {
			
			public void run() {
				Utils.ShowToast(getApplicationContext(), getString(R.string.sync_success)
						+ ", " + upload + " " + getString(R.string.uploaded)
						+ ", " + download + " " + getString(R.string.downloaded)
						+ " " + getString(R.string.from_dropbox));
			}
		});
		
		
	}

	public void onSyncDriveDone(final int upload, final int download) {
		runOnUiThread(new Runnable() {
			
		public void run() {
			Utils.ShowToast(getApplicationContext(), getString(R.string.sync_success)
					+ ", " + upload + " " + getString(R.string.uploaded)
					+ ", " + download + " " + getString(R.string.downloaded)
					+ " " + getString(R.string.from_google_drive));
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case REQUEST_AUTHORIZATION:
			if (resultCode == Activity.RESULT_OK) {
			}
			break;
		}
	}
	
	int getRateStatus() {
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		return pref.getInt(kRateKey, 0);
		
	}
	
	void setRateStatus(int rateStatus) {
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		Editor editor = pref.edit();
		editor.putInt(kRateKey, rateStatus);
		editor.commit();
	}
	
	void updateAndShowRateRequestIfNeed() {
	    int rateStatus = getRateStatus();
	    Log.d("", "Rate status: " + rateStatus);
	    
	    if((rateStatus != kRateStatusDontAskAgain && rateStatus != kRateStatusRated) && rateStatus >= kRateStatusToAskRate) {
	        new AlertDialog.Builder(this)
	        .setTitle(R.string.alert)
	        .setMessage(R.string.rate_message)
	        .setPositiveButton(R.string.rate_now, new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					setRateStatus(kRateStatusRated);
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=com.nch.smsbackupandrestore"));
					startActivity(intent);
				}
			})
	        .setNeutralButton(R.string.remind_me_later, new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					setRateStatus(0);
				}
			})
			.setNegativeButton(R.string.dont_ask_again, new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					setRateStatus(kRateStatusDontAskAgain);
				}
			})
			.show();
	        
	    }
	    
	    if(rateStatus >= 0) {
	        rateStatus++;
	        setRateStatus(rateStatus);
	    }
	}
}